package pl.koziczak.knowledgeintegration.model.builder;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import pl.koziczak.knowledgeintegration.exception.KnowledgeIntegrationException;
import pl.koziczak.knowledgeintegration.model.Class;
import pl.koziczak.knowledgeintegration.model.Element;

public class DocumentBuilder {
	
	private static DocumentBuilder instance;
	
	private DocumentBuilder(){
		// SINGLETON
	}

	public static DocumentBuilder getInstance() {
		if(instance == null)
			instance = new DocumentBuilder();
		return instance;
	}
	
	public Document build(Class c) throws KnowledgeIntegrationException {
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		javax.xml.parsers.DocumentBuilder docBuilder = null;
		try {
			docBuilder = docFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new KnowledgeIntegrationException(e);
		}
		
		Document doc = docBuilder.newDocument();
		
		doc.appendChild(createNode(c, doc));
		
		return doc;
	}
	
	private Node createNode(Class c, Document doc) {
		org.w3c.dom.Element node = doc.createElement(c.getName());
		/*
		 * add element
		 */
		for(Element e : c.getElements()) {
			if(!e.isAttribute())
				node.appendChild(createNode(e, doc));
			else
				node.setAttributeNode(createAttr(e, doc));
		}
		/*
		 * add subClass
		 */
		for(Class cl: c.getSubClasses()) {
			node.appendChild(createNode(cl, doc));
		}
		return node;
	}
	
	private Node createNode(Element e, Document doc) {
		Node node = doc.createElement(e.getName());
		node.appendChild(doc.createTextNode(e.getValue()));
		node.setNodeValue(e.getValue());
		return node;
	}
	
	private Attr createAttr(Element e, Document doc) {
		Attr attr = doc.createAttribute(e.getName());
		attr.setValue(e.getValue());
		return attr;
	}
}
